package com.ysstech.reportworld.service.impl;

import com.ysstech.reportworld.service.WeComService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

/**
 * 企业微信机器人发送短信
 */
@Service
@Slf4j
public class WeComServiceImpl implements WeComService {

    /**
     * 企业微信机器人发送短信
     */
    public void sendMessage(String url, String message) throws Exception {
        try {
            if (StringUtils.isBlank(url) || StringUtils.isBlank(message)) {
                return;
            }
         /*   url = "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=23e0f483-41fc-4f3e-bdcf-e66314ccaa10";
            message = "测试机器人";*/
            HttpHeaders header = new HttpHeaders();
            header.setContentType(MediaType.APPLICATION_JSON);
            header.set("Authorization", "APPCODE_PD");

            Map<String, Object> requestParam = new HashMap<>();
            Map<String, Object> content = new HashMap<>();
            content.put("content", message);

            requestParam.put("msgtype", "text");
            requestParam.put("text", content);
            HttpEntity<Map<String, Object>> request = new HttpEntity<Map<String, Object>>(requestParam, header);

            RestTemplate restTemplate = new RestTemplate();
            restTemplate.getMessageConverters().set(1, new StringHttpMessageConverter(StandardCharsets.UTF_8));
            restTemplate.postForEntity(url, request, String.class);
        } catch (Exception ex) {
            log.error("发送消息失败。" + ex.getMessage());
        }
    }
}
